package com.hn.vue.controller;

import com.hn.vue.param.UserParam;
import com.hn.vue.pojo.User;
import com.hn.vue.service.UserService;
import com.hn.vue.util.PoiUtil;
import com.hn.vue.vo.PageVo;
import com.hn.vue.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * hanni
 * 2019/2/28 0028
 * 18:59
 */

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询用户列表
     * @return
     */
    @GetMapping("/list")
    public PageVo<User> userList(UserParam userParam){

        return userService.findUserList(userParam);
    }

    @PostMapping
    public ResponseVo saveUser(User user){

        try {
            userService.saveUser(user);
        }catch (Exception e){

            return ResponseVo.error("用户添加失败");
        }
        return ResponseVo.ok("用户编辑成功");
    }

    @GetMapping("/delete")
    public ResponseVo delete(String idd){
        System.out.println(idd);
        try {

            String[] split = idd.split(",");

            for (String s : split) {
                long l = Long.parseLong(s);
            }
//
//            userService.delete(rowid);

        }catch (Exception e){

            return ResponseVo.error("用户添加失败");
        }
        return ResponseVo.ok("用户编辑成功");


    }

    @GetMapping("/export")
    public ResponseEntity<byte[]> export() throws Exception {

        HttpStatus status = HttpStatus.OK;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息.xls", "utf-8"));

        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        List<User> data = userService.findAllUsers();
        PoiUtil.exportExecl(bao, Arrays.asList("ID", "用户名", "邮箱", "手机号", "角色"), Arrays.asList("id", "name", "email", "mobile", "roles"), data);

        byte[] body = bao.toByteArray();//把输出流的数据转成字节数组
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body, headers, status);
        return responseEntity;

    }


}
